""" 
read switch 干簧管传感器
接线:
    DO --> GPIO26 : 
        无磁铁靠近时,DO输出高电平
        磁铁靠近时,DO输出低电平
    VCC --> 3.3 ~ 5.0V
    GND --> GND

说明: https://blog.csdn.net/weixin_42645653/article/details/112239737
"""

from machine import Pin
import time

readswitch_pinNum = 26  # 传感器DO 输入
led_pinNum = 15  # LED端口
led_pin = None
test_mode = "irq"
test_mode = "read_input"


def read_input(read_pin):
    while True:
        value = read_pin.value()
        if value == 1:
            led_pin.value(0)
            print("无磁铁靠近 ---")
        else:
            led_pin.value(1)
            print("磁铁靠近 +++")
        time.sleep(1)

def irq_call_back(irq_pin):
    value = irq_pin.value()
    """ 磁铁靠近 -- 低电平触发 """
    if value == 1:
        led_pin.value(0)
        print("无磁铁靠近 ---")
    else:
        led_pin.value(1)
        print("磁铁靠近 +++")


# 程序入口
if __name__ == "__main__":
    readswitch_pin = Pin(readswitch_pinNum, Pin.IN, Pin.PULL_UP)  # 输入上拉,默认高电平
    led_pin = Pin(led_pinNum, Pin.OUT)  # 输出
    led_pin.value(0)
    if test_mode == 'irq':
        readswitch_pin.irq(trigger=Pin.IRQ_FALLING, handler=irq_call_back)  # 上升沿触发
        while True:
            pass
    else:
        read_input(readswitch_pin)
